package com.samsung.common.util;

import java.security.MessageDigest;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import com.samsung.model.user.User;

/**
 * 工具类
* @author zq.wu
* @class BaseUtil   
* @remark       
* @date 2015-4-7 下午01:41:35
 */
public class BaseUtil {
	
	public static String getUUID(){
		String uuid = UUID.randomUUID().toString(); 
        return uuid.substring(0,8) + uuid.substring(9,13) + uuid.substring(14,18) + uuid.substring(19,23) + uuid.substring(24); 
	}
	
	public static boolean isEmpty(String str){
		return (str == null || "".equals(str)); 
	}
	
	public static boolean isNotEmpty(String str){
		return !isEmpty(str);
	}
	
	/**
	 * 
	* @Title: md5
	* @Description: md5加密方法
	* @param @param s
	* @param @return    设定文件
	* @return String    返回类型
	* @throws
	 */
	public final static String md5(String s) {
		if(s==null) {
			return null;
		}
		char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
				'A', 'B', 'C', 'D', 'E', 'F' };
		try {
			byte[] btInput = s.getBytes();
			// 获得MD5摘要算法的 MessageDigest 对象
			MessageDigest mdInst = MessageDigest.getInstance("MD5");
			// 使用指定的字节更新摘要
			mdInst.update(btInput);
			// 获得密文
			byte[] md = mdInst.digest();
			// 把密文转换成十六进制的字符串形式
			int j = md.length;
			char str[] = new char[j * 2];
			int k = 0;
			for (int i = 0; i < j; i++) {
				byte byte0 = md[i];
				str[k++] = hexDigits[byte0 >>> 4 & 0xf];
				str[k++] = hexDigits[byte0 & 0xf];
			}
			return new String(str);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	/**
	 * 
	* @Title: getRemoteHost
	* @Description:  获取客户端IP
	* @param @param request
	* @param @return    设定文件
	* @return String    返回类型
	* @throws
	 */
	public static String getRemoteHost(javax.servlet.http.HttpServletRequest request){
	    String ip = request.getHeader("x-forwarded-for");
	    if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
	        ip = request.getHeader("Proxy-Client-IP");
	    }
	    if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
	        ip = request.getHeader("WL-Proxy-Client-IP");
	    }
	    if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
	        ip = request.getRemoteAddr();
	    }
	    return ip.equals("0:0:0:0:0:0:0:1")?"127.0.0.1":ip;
	}
	
	/**
	 * 
	 * @Title: getLoginedUser
	 * @Description:  获取session中当前登录用户
	 * @param @param request
	 * @param @return    设定文件
	 * @return User    返回类型
	 * @throws
	 */
	public static User getLoginedUser(HttpServletRequest request){
		Object obj = request.getSession().getAttribute(Constant.LOGIN_TOKEN);
		if(obj == null) {
			return null;
		}
		return (User) obj;
	}

	public static void main(String[] args) {
		System.out.println(md5("123456"));
	}
	
}
